#include "systemInfoHandler.h"
#include "cpuSimulator.h"
#include <QDateTime>

/**
 * @brief SystemInfoHandler构造函数
 */
SystemInfoHandler::SystemInfoHandler(QObject *parent)
    : SystemCallHandler(parent)
    , randomGenerator(QRandomGenerator::global())
    , totalMemorySize(DEFAULT_MEMORY_SIZE)
    , allocatedMemorySize(0)
    , memoryBaseAddress(0x10000)
    , nextAllocationAddress(memoryBaseAddress)
    , isShutdownRequested(false)
    , isRebootRequested(false)
    , systemStartTime(QDateTime::currentMSecsSinceEpoch())
    , simulatedSystemTime(QDateTime::currentDateTime())
    , cpuUsageUpdateCounter(0)
{
    systemUptime.start();
}

/**
 * @brief SystemInfoHandler析构函数
 */
SystemInfoHandler::~SystemInfoHandler()
{
    // 清理所有分配的内存块
    memoryBlocks.clear();
    freeMemoryAddresses.clear();
}

/**
 * @brief 处理中断调用
 * @param interruptNumber 中断号
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult SystemInfoHandler::handleInterrupt(int interruptNumber, CpuSimulator* cpu)
{
    if (!isInterruptSupported(interruptNumber)) {
        return createErrorResult(-1, "不支持的系统信息中断号");
    }
    
    switch (interruptNumber) {
        // 系统信息中断
        case 0x50: return handleGetSystemTime(cpu);
        case 0x51: return handleGetSystemDate(cpu);
        case 0x52: return handleGetTimestamp(cpu);
        case 0x53: return handleDelay(cpu);
        case 0x54: return handleGetMemoryUsage(cpu);
        case 0x55: return handleGetCpuUsage(cpu);
        case 0x56: return handleSystemReboot(cpu);
        case 0x57: return handleSystemShutdown(cpu);
        case 0x58: return handleGetUptime(cpu);
        case 0x59: return handleSetSystemTime(cpu);
        case 0x5A: return handleGetRandomSeed(cpu);
        case 0x5B: return handleSetRandomSeed(cpu);
        
        // 内存管理中断
        case 0x60: return handleMemoryAllocate(cpu);
        case 0x61: return handleMemoryFree(cpu);
        case 0x62: return handleMemoryCopy(cpu);
        case 0x63: return handleMemoryFill(cpu);
        case 0x64: return handleMemoryCompare(cpu);
        case 0x65: return handleGetMemoryInfo(cpu);
        case 0x66: return handleMemoryReallocate(cpu);
        case 0x67: return handleMemoryAlignedAllocate(cpu);
        case 0x68: return handleGetMemoryFragmentation(cpu);
        case 0x69: return handleMemoryCompression(cpu);
        
        default:
            return createErrorResult(-1, QString("未实现的系统信息中断: 0x%1").arg(interruptNumber, 2, 16, QChar('0')));
    }
}

/**
 * @brief 获取支持的中断号范围
 * @return QPair<int, int> 中断号范围
 */
QPair<int, int> SystemInfoHandler::getSupportedInterruptRange() const
{
    return qMakePair(0x50, 0x69);
}

/**
 * @brief 获取处理器描述
 * @return QString 描述信息
 */
QString SystemInfoHandler::getDescription() const
{
    return "系统信息和内存管理处理器 - 支持时间、日期、内存管理等系统功能";
}

/**
 * @brief 重置处理器状态
 */
void SystemInfoHandler::reset()
{
    // 清理所有内存分配
    memoryBlocks.clear();
    freeMemoryAddresses.clear();
    
    // 重置内存管理状态
    allocatedMemorySize = 0;
    nextAllocationAddress = memoryBaseAddress;
    
    // 重置系统状态
    isShutdownRequested = false;
    isRebootRequested = false;
    systemStartTime = QDateTime::currentMSecsSinceEpoch();
    simulatedSystemTime = QDateTime::currentDateTime();
    
    // 重启系统运行时间计时器
    systemUptime.restart();
    
    // 清空CPU使用率历史
    cpuUsageHistory.clear();
    cpuUsageUpdateCounter = 0;
}

// 基本实现一些关键方法
SystemCallResult SystemInfoHandler::handleGetSystemTime(CpuSimulator* cpu)
{
    QDateTime currentTime = QDateTime::currentDateTime();
    QTime time = currentTime.time();
    
    QMap<QString, int> result;
    result["AX"] = time.hour();
    result["BX"] = time.minute();
    result["CX"] = time.second();
    
    return createSuccessResult(result);
}

SystemCallResult SystemInfoHandler::handleGetSystemDate(CpuSimulator* cpu)
{
    QDateTime currentDate = QDateTime::currentDateTime();
    QDate date = currentDate.date();
    
    QMap<QString, int> result;
    result["AX"] = date.year();
    result["BX"] = date.month();
    result["CX"] = date.day();
    
    return createSuccessResult(result);
}

SystemCallResult SystemInfoHandler::handleGetMemoryUsage(CpuSimulator* cpu)
{
    QMap<QString, int> result;
    result["AX"] = allocatedMemorySize;
    result["BX"] = totalMemorySize;
    
    return createSuccessResult(result);
}

// 占位实现其他方法
SystemCallResult SystemInfoHandler::handleGetTimestamp(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleDelay(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleGetCpuUsage(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleSystemReboot(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleSystemShutdown(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleGetUptime(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleSetSystemTime(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleGetRandomSeed(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleSetRandomSeed(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleMemoryAllocate(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleMemoryFree(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleMemoryCopy(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleMemoryFill(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleMemoryCompare(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleGetMemoryInfo(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleMemoryReallocate(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleMemoryAlignedAllocate(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleGetMemoryFragmentation(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult SystemInfoHandler::handleMemoryCompression(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }

// 辅助方法的占位实现
void SystemInfoHandler::setTotalMemory(int totalMemory) { totalMemorySize = totalMemory; }
QPair<int, int> SystemInfoHandler::getMemoryStats() const { return qMakePair(allocatedMemorySize, totalMemorySize); }
int SystemInfoHandler::findAvailableMemoryBlock(int size, int alignment) { Q_UNUSED(size) Q_UNUSED(alignment) return -1; }
bool SystemInfoHandler::allocateMemoryBlock(int address, int size) { Q_UNUSED(address) Q_UNUSED(size) return false; }
bool SystemInfoHandler::freeMemoryBlock(int address) { Q_UNUSED(address) return false; }
MemoryBlock* SystemInfoHandler::findMemoryBlock(int address) { Q_UNUSED(address) return nullptr; }
void SystemInfoHandler::mergeAdjacentFreeBlocks() { /* 占位实现 */ }
QPair<int, int> SystemInfoHandler::calculateFragmentation() const { return qMakePair(0, 0); }
bool SystemInfoHandler::isValidMemoryAddress(int address, int size) const { Q_UNUSED(address) Q_UNUSED(size) return true; }
int SystemInfoHandler::simulateCpuUsage() { return 50; } // 模拟50%使用率
int SystemInfoHandler::performDelay(int milliseconds) { Q_UNUSED(milliseconds) return 0; } 